const UserModel = require('../model/user')
const bcrypt = require('bcryptjs');

module.exports = {
  async signup(ctx, next) {
    if (ctx.method === 'GET') {
      await ctx.render('signup', {
        title: '注册页面'
      })
    } else {
      let { name, email, password } = ctx.request.body
      const salt = bcrypt.genSaltSync(10); // 加盐次数
      password = bcrypt.hashSync(password, salt);

      const user = {
        name,
        email,
        password
      }
      const result = await UserModel.create(user) // 让数据库具有这样一张表
      ctx.body = result
    }
  },
  // 登录
  async signin(ctx, next) {
    if (ctx.method === 'GET') {
      ctx.session = null
      await ctx.render('signin', {
        title: '登录页面'
      })
    } else {
      const { name, password } = ctx.request.body
      const user = await UserModel.findOne({ name })
      if (user && await bcrypt.compare(password, user.password)) {
        ctx.session.user = {
          _id: user._id,
          name: user.name,
          isAdmin: user.isAdmin,
          email: user.email
        }
        ctx.flash = {
          success: '登录成功'
        }

        ctx.redirect('/')
      } else {
        ctx.flash = {
          warning: '登录失败'
        }
        ctx.body = '用户名或密码错误'
      }
    }
  },
  // 退出
  signout(ctx, next) {
    ctx.session.user = null
    ctx.flash = { warning: '退出登录' }
    ctx.redirect('/')
  }
}